{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ec51f656",
   "metadata": {},
   "source": [
    "# Azure OpenAI"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ef3d26db",
   "metadata": {},
   "source": [
    "Azure openAI resources unfortunately differ from standard openAI resources as you can't generate embeddings unless you use an embedding model. The regions where these models are available can be found here: https://learn.microsoft.com/en-us/azure/cognitive-services/openai/concepts/models#embeddings-models\n",
    "\n",
    "Furthermore the regions that support embedding models unfortunately don't support the latest versions (<*>-003) of openAI models, so we are forced to use one region for embeddings and another for the text generation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "b05e71d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "import openai\n",
    "from langchain.embeddings import OpenAIEmbeddings\n",
    "from llama_index.llms import AzureOpenAI\n",
    "from llama_index import LangchainEmbedding\n",
    "from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext\n",
    "import logging\n",
    "import sys\n",
    "\n",
    "logging.basicConfig(\n",
    "    stream=sys.stdout, level=logging.INFO\n",
    ")  # logging.DEBUG for more verbose output\n",
    "logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "80a962f8",
   "metadata": {},
   "source": [
    "This is the API setup for the embedding model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "fe013749",
   "metadata": {},
   "outputs": [],
   "source": [
    "openai.api_type = \"azure\"\n",
    "openai.api_base = \"<insert api base url from azure>\"\n",
    "openai.api_version = \"2022-12-01\"\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"<insert api key from azure>\"\n",
    "openai.api_key = os.getenv(\"OPENAI_API_KEY\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "fcaaafdf",
   "metadata": {},
   "source": [
    "And here you can see the setup for the text generation model, you should note we use deployment name instead of model name as an arguement. This name is the one chosen when deploying the model in Azure."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e2569cb0",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = AzureOpenAI(engine=\"<insert deployment name from azure>\", mode=\"model name\")\n",
    "\n",
    "# You need to deploy your own embedding model as well as your own chat completion model\n",
    "embedding_llm = LangchainEmbedding(\n",
    "    OpenAIEmbeddings(\n",
    "        model=\"text-embedding-ada-002\",\n",
    "        deployment=\"<insert EMBEDDING model deployment name from azure>\",\n",
    "        openai_api_key=openai.api_key,\n",
    "        openai_api_base=openai.api_base,\n",
    "        openai_api_type=openai.api_type,\n",
    "        openai_api_version=openai.api_version,\n",
    "    ),\n",
    "    embed_batch_size=1,\n",
    ")\n",
    "\n",
    "documents = SimpleDirectoryReader(\"../paul_graham_essay/data\").load_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72aac5a6-495e-40d2-82d3-bda8688ae919",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index import set_global_service_context\n",
    "\n",
    "service_context = ServiceContext.from_defaults(\n",
    "    llm=llm,\n",
    "    embed_model=embedding_llm,\n",
    ")\n",
    "\n",
    "set_global_service_context(service_context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "1cf0e9c9",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "> Adding chunk: \t\t\n",
      "\n",
      "What I Worked On\n",
      "\n",
      "February 2021\n",
      "\n",
      "Before col...\n",
      "> Adding chunk: interesting of that type. So I'm not surprised ...\n",
      "> Adding chunk: to be the study of the ultimate truths, compare...\n",
      "> Adding chunk: language called PL/I, and the situation was sim...\n",
      "> Adding chunk: or if there even was a specific moment, but dur...\n",
      "> Adding chunk: an uneasy alliance between two halves, theory a...\n",
      "> Adding chunk: were hundreds of years old.\n",
      "\n",
      "And moreover this ...\n",
      "> Adding chunk: that he'd found such a spectacular way to get o...\n",
      "> Adding chunk: the classes that everyone has to take in fundam...\n",
      "> Adding chunk: students wouldn't require the faculty to teach ...\n",
      "> Adding chunk: or you get merely photographic accuracy, and wh...\n",
      "> Adding chunk: But the Accademia wasn't teaching me anything e...\n",
      "> Adding chunk: In Florence, after paying my part of the rent, ...\n",
      "> Adding chunk: about a new thing called HTML, which was, as he...\n",
      "> Adding chunk: were plenty of earnest students too: kids who \"...\n",
      "> Adding chunk: Lisp hacking work was very rare, and I didn't w...\n",
      "> Adding chunk: had done for the popularity of microcomputers. ...\n",
      "> Adding chunk: shopping cart, and I wrote a new site generator...\n",
      "> Adding chunk: seed funding from Idelle's husband Julian. In r...\n",
      "> Adding chunk: for a month,\" he said, \"and it's still not done...\n",
      "> Adding chunk: fun to work on. If all I'd had to do was work o...\n",
      "> Adding chunk: the collar than a picture of the whole shirt. T...\n",
      "> Adding chunk: partly because that's what startups did during ...\n",
      "> Adding chunk: had given us a lot of options when they bought ...\n",
      "> Adding chunk: That's what I should have done, just gone off s...\n",
      "> Adding chunk: buy. Now I could actually choose what neighborh...\n",
      "> Adding chunk: trying to build what it's now clear is about tw...\n",
      "> Adding chunk: dream of building a new Lisp, partly because on...\n",
      "> Adding chunk: me several years to understand the implications...\n",
      "> Adding chunk: seems about as hip.\n",
      "\n",
      "It's not that unprestigiou...\n",
      "> Adding chunk: charge of marketing at a Boston investment bank...\n",
      "> Adding chunk: out \"But not me!\" and went on with the talk. Bu...\n",
      "> Adding chunk: And neither of them helped founders enough in t...\n",
      "> Adding chunk: fake investors, because they would in a similar...\n",
      "> Adding chunk: batch was so good. You had to be pretty bold to...\n",
      "> Adding chunk: had not originally intended YC to be a full-tim...\n",
      "> Adding chunk: internal software in Arc. But while I continued...\n",
      "> Adding chunk: double from a kidney stone, he suggested that i...\n",
      "> Adding chunk: we agreed to make it a complete changing of the...\n",
      "> Adding chunk: of 2014 painting. I'd never been able to work s...\n",
      "> Adding chunk: his grad student Steve Russell suggested it. Ru...\n",
      "> Adding chunk: defined goal, or it would have been hard to kee...\n",
      "> Adding chunk: pools. It felt like I was doing life right. I r...\n",
      "> Adding chunk: the more exciting.\n",
      "\n",
      "[2] Italian words for abstr...\n",
      "> Adding chunk: expensive.\n",
      "\n",
      "[7] Technically the apartment wasn'...\n",
      "> Adding chunk: online means you treat the online version as th...\n",
      "> Adding chunk: logo had been a white V on a red circle, so I m...\n",
      "> Adding chunk: YC was not working with Jessica anymore. We'd b...\n",
      "> [build_index_from_documents] Total LLM token usage: 0 tokens\n",
      "> [build_index_from_documents] Total embedding token usage: 17533 tokens\n"
     ]
    }
   ],
   "source": [
    "index = VectorStoreIndex.from_documents(documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "98d9d3fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "> [query] Total LLM token usage: 815 tokens\n",
      "> [query] Total embedding token usage: 8 tokens\n",
      "> Source (Doc id: ad03b507-8953-4201-b545-6195c5cfec49): me several years to understand the implications. It meant there would be a whole new generation o...\n",
      "query was: What is most interesting about this essay?\n",
      "answer was: \n",
      "\n",
      "The most interesting thing about this essay is the way the author reflects on the impact of online publishing on their life and career. They discuss how the opening up of the internet to allow for more diverse, and less prestigious, forms of writing allowed them to pursue the kind of writing they were interested in, which was something that had not been possible before. Furthermore, the author acknowledges that their work may not be seen as prestigious, such as Latin, but yet still has a great impact. They further reflect on how their life and career have been shaped by working on these types of projects.\n"
     ]
    }
   ],
   "source": [
    "query = \"What is most interesting about this essay?\"\n",
    "query_engine = index.as_query_engine()\n",
    "answer = query_engine.query(query)\n",
    "\n",
    "print(answer.get_formatted_sources())\n",
    "print(\"query was:\", query)\n",
    "print(\"answer was:\", answer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3e33f1eb",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}